package com.example.victory.service;

import com.example.victory.entity.companyEntity.TargetStatusEntity;
import com.example.victory.mapper.CustomerMapper;
import com.example.victory.entity.companyEntity.SalaryStatusEntity;
import com.example.victory.swagger.handler.AppStaffSalaryApiDelegate;
import com.example.victory.swagger.model.*;
import com.example.victory.utils.CrmUtils;
import com.example.victory.common.web.ServiceHelper;
import com.cgws.fintech.sdk.inner.utils.web.SessionService;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 员工薪酬
 */
@Slf4j
@Service
public class StaffSalaryService implements AppStaffSalaryApiDelegate {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private SessionService sessionService;

    @Value("${app.is.crm.product:true}")
    private boolean isCrmProduct;

    @Override
    public ResponseEntity<ApiResponseQuerySalaryDate> getQuerySalaryDate() {
        ApiResponseQuerySalaryDateData data = new ApiResponseQuerySalaryDateData();

        List<KeyValueDetail> keyValueDetailList = Lists.newArrayList();
        for (int i = 0; i < 6; i++) {
            setKeyValue(keyValueDetailList, i);
        }
        data.setQueryDate(keyValueDetailList);
        return ResponseEntity.ok(new ApiResponseQuerySalaryDate().data(data));
    }

    private void setKeyValue(List<KeyValueDetail> keyValueDetailList, int month) {
        KeyValueDetail keyValueDetail = new KeyValueDetail();
        String lastTwoMonths = getLastMonths(month);
        keyValueDetail.setName(lastTwoMonths.replace("-",""));
        keyValueDetail.setValue(lastTwoMonths.replace("-", "."));
        keyValueDetailList.add(keyValueDetail);
    }

    /**
     * 获取上i个月
     * @param i 上几个月
     * @return 上几个月字符串
     */
    private String getLastMonths(int i) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -i);
        Date m = c.getTime();
        return sdf.format(m);
    }

    @Override
    public ResponseEntity<ApiResponseGetStaffSalaryInfo> getStaffSalaryInfo(ApiRequestStaffSalary param) {
        ApiRequestStaffSalaryData data = param.getData();
        ServiceHelper.checkDataNotNull(data, "data");
        Integer month = data.getMonth();
        if (month == null) {// 为null则查上月工资
            month =  Integer.parseInt(getLastMonths(1).replace("-", ""));
        }

        // crm 测试环境里只有201901有数据
        if (!isCrmProduct) {
            month = 201901;
        }

        // 获取ryid
        Integer ryid = CrmUtils.getCustomerAccount(sessionService.getCurrentUserSession(true).getUser());

        ApiResponseGetStaffSalaryInfoData infoData = new ApiResponseGetStaffSalaryInfoData();
        // 获取目标完成情况
        List<TargetInfo> targetStatus = getTargetStatus(ryid, month);
        // 获取个人薪酬的相关信息
        SalaryInfo salaryInfo = getSalaryStatus(ryid, month);
        // 核心考核项目信息
        List<CoreAssessItems> coreAssessmentItems = getCoreAssessmentItems(ryid, month);
        // 考核加减分项信息
        List<AssessAddOrSubPoint> assessmentAddOrSubPoint = getAssessmentAddOrSubPoint(ryid, month);

        infoData.setQueryDate(month);
        infoData.setTargetInfo(targetStatus);
        if (salaryInfo != null) {
            infoData.setMySalary(salaryInfo.getMySalary());
            infoData.setSalaryInfo(salaryInfo.getSalaryInfo());
        }
        infoData.setCoreAssessItems(coreAssessmentItems);
        infoData.setAssessAddOrSubPoint(assessmentAddOrSubPoint);

        return ResponseEntity.ok(new ApiResponseGetStaffSalaryInfo().data(infoData));
    }

    @Data
    private class SalaryInfo {
        String mySalary;
        List<KeyValueDetail> salaryInfo;
    }

    /**
     * 获取绩效考核信息
     * @param month 月份
     * @return  考核加减分项信息
     */
    private List<AssessAddOrSubPoint> getAssessmentAddOrSubPoint(Integer ryid, Integer month) {
        List<AssessAddOrSubPoint> assessAddOrSubPoints = customerMapper.getAssessmentAddOrSubPoint(ryid, month);
        if (assessAddOrSubPoints == null || assessAddOrSubPoints.size() == 0) {
            return null;
        }
        Double assessAddOrSubPointsTotal = 0.00;
        for (AssessAddOrSubPoint addOrSubPoint: assessAddOrSubPoints) {
            String score = addOrSubPoint.getTargetValue().trim();
            if (score.startsWith(".")) addOrSubPoint.setTargetValue("0" + score);
            assessAddOrSubPointsTotal += Double.parseDouble(score);
            String repace = addOrSubPoint.getAssessProject().replace("人员_","");
            addOrSubPoint.setAssessProject(repace);
        }

        AssessAddOrSubPoint addOrSubPoint = new AssessAddOrSubPoint();
        addOrSubPoint.setAssessProject("总得分");
        String total = String.format("%.2f", assessAddOrSubPointsTotal);
        addOrSubPoint.setTargetValue(total);
        assessAddOrSubPoints.add(addOrSubPoint);

        return assessAddOrSubPoints;
    }

    /**
     * 获取绩效考核信息
     * @param month  月份
     * @return  核心考核项目信息
     */
    private List<CoreAssessItems> getCoreAssessmentItems(Integer ryid, Integer month) {
        List<CoreAssessItems> coreAssessItems = customerMapper.getCoreAssessmentItems(ryid, month);
        if (coreAssessItems == null || coreAssessItems.size() == 0) {
            return null;
        }

        Double coreAssessItemsTotal = 0.00;
        for (CoreAssessItems coreAssessItem: coreAssessItems) {
            String score = coreAssessItem.getScore().trim();
            if (score.startsWith(".")) coreAssessItem.setScore("0" + score);
            coreAssessItemsTotal += Double.parseDouble(score);
            if (coreAssessItem.getTargetValue().contains(".")) {
                coreAssessItem.setTargetValue(formatThousandSeparatorPoint(coreAssessItem.getTargetValue()));
            } else {
                coreAssessItem.setTargetValue(formatThousandSeparator(coreAssessItem.getTargetValue()));
            }
        }

        CoreAssessItems cai = new CoreAssessItems();
        cai.setAssessProject("总得分");
        String total = String.format("%.2f", coreAssessItemsTotal);
        cai.setScore(total);
        coreAssessItems.add(cai);

        return coreAssessItems;
    }

    /**
     * 格式化千分位
     */
    private String formatThousandSeparator(String num) {
        DecimalFormat decimalFormat = new DecimalFormat(",###");
        return decimalFormat.format(new BigDecimal(num));
    }

    /**
     * 格式化千分位(带小数点)
     */
    private String formatThousandSeparatorPoint(String num) {
        DecimalFormat decimalFormat = new DecimalFormat(",##0.00");
        return decimalFormat.format(new BigDecimal(num));
    }

    /**
     * 获取个人薪酬的相关信息
     * @param month 月份
     * @return  个人薪酬的相关信息
     */
    private SalaryInfo getSalaryStatus(Integer ryid, Integer month) {
        SalaryStatusEntity entity = customerMapper.getSalaryStatus(ryid, month);
        if (entity == null) {
            return null;
        }

        SalaryInfo salaryInfo = new SalaryInfo();
        salaryInfo.setMySalary(entity.getYfgz());

        List<KeyValueDetail>  items = Lists.newArrayList();
        setKeyValue(items, "基本工资", entity.getJbgz());
        setKeyValue(items, "固定工资", entity.getGdgz());
        setKeyValue(items, "浮动工资", entity.getFdgz());
        setKeyValue(items, "工资调整项", entity.getGztzx());
        setKeyValue(items, "管理客户服务提成", entity.getGlkhfwtc());
        setKeyValue(items, "期权佣金提成", entity.getQqyjtc());
        setKeyValue(items, "营销服务提成包", entity.getYxfwtcb());
        setKeyValue(items, "营销佣金提成", entity.getYxyjtc());
        setKeyValue(items, "投顾服务增量收益", entity.getTgfwzlsy());
        setKeyValue(items, "开户奖", entity.getKhj());
        setKeyValue(items, "考核得分", entity.getKhdf());
        setKeyValue(items, "管理津贴", entity.getGljt());
        setKeyValue(items, "社保扣款", entity.getSbkk());
        setKeyValue(items, "企业年金扣款", entity.getQynjkk());
        setKeyValue(items, "其他扣款", entity.getQtkk());
        setKeyValue(items, "应扣合计", entity.getYkhj());
        setKeyValue(items, "应税所得", entity.getYssd());
        setKeyValue(items, "个人所得税", entity.getGrsds());
        setKeyValue(items, "风险金扣缴数额", entity.getFxjkjse());
        setKeyValue(items, "税后调整项", entity.getShtzx());
        setKeyValue(items, "应发工资", entity.getYfgz());
        setKeyValue(items, "实发工资", entity.getSfgz());

        salaryInfo.setSalaryInfo(items);
        return salaryInfo;
    }

    //设置key-value
    private void setKeyValue(List<KeyValueDetail>  items, String key, String value) {
        KeyValueDetail keyValueDetail = new KeyValueDetail();
        keyValueDetail.setName(key);
        keyValueDetail.setValue(value);
        items.add(keyValueDetail);
    }

    //求两数比例
    private static String percnet(String d,String e){
        d = d.replace(",", "");
        e = e.replace(",", "");
        double p = Double.parseDouble(d)/Double.parseDouble(e);
        DecimalFormat nf = (DecimalFormat) NumberFormat.getPercentInstance();
//        nf.applyPattern("00%"); //00表示小数点前2位
        nf.setMaximumFractionDigits(2); //2表示精确到小数点后2位
        nf.setGroupingUsed(false);      // 去掉千分位的逗号
        return nf.format(p);
    }

    private void setTargetInfo(List<TargetInfo> targetInfos, String targetProject, String targetValue, String competeValue) {

        TargetInfo targetInfo = new TargetInfo();
        targetInfo.setTargetProject(targetProject);
        if (Objects.equals(targetProject, "新开户净增资产")) {
            targetInfo.setTargetValue(formatThousandSeparator(targetValue));
            targetInfo.setCompleteValue(formatThousandSeparator(competeValue));
        } else {
            targetInfo.setTargetValue(targetValue);
            targetInfo.setCompleteValue(competeValue);
            if (!Objects.equals(targetValue, "0")) {
                targetInfo.setTargetValue(formatThousandSeparatorPoint(targetValue.trim()));
            }
            if (!Objects.equals(competeValue, "0")) {
                targetInfo.setCompleteValue(formatThousandSeparatorPoint(competeValue.trim()));
            }
        }
        if (Objects.equals(competeValue, "0")) {
            targetInfo.setCompleteRate("0%");
        } else if (Objects.equals(targetValue, "0") && !Objects.equals(competeValue, "0")) {
            targetInfo.setCompleteRate("100%");
        } else {
            targetInfo.setCompleteRate(percnet(competeValue, targetValue));
        }
        targetInfos.add(targetInfo);
    }

    /**
     * 获取个人的目标及完成情况信息
     * @param month 月份
     * @return  目标及完成情况信息
     */
    private List<TargetInfo> getTargetStatus(Integer ryid, Integer month) {
        TargetStatusEntity entity = customerMapper.getTargetStatus(ryid,month);
        if (entity == null) {
            return null;
        }
        List<TargetInfo> targetInfos = Lists.newArrayList();
        setTargetInfo(targetInfos, "新开户净增有效户", entity.getNewValidAccountTask(), entity.getNewValidAccount());
        setTargetInfo(targetInfos, "新开户净增资产", entity.getNewIncreaseAssetTask(), entity.getNewIncreaseAsset());
        setTargetInfo(targetInfos, "月金融产品销售量", entity.getMonthSalesTask(), entity.getMonthSales());
        setTargetInfo(targetInfos, "年金融产品销售量", entity.getAnnualSalesTask(), entity.getAnnualSales());

        return targetInfos;
    }
}
